<?php
/**
 *
 *
 * 替换订单时实例化
 *
 *
 *
 */
class ome_order_replace{
    /**
     * @param $order_items
     * @param $shop_id
     * @return array|bool
     */
    public function inreplace($order_items,$shop_id){
        $pre_nums=$order_items['nums'];
        if(empty($order_items)) return false;
        $replaceMdl = app::get('material')->model('basic_replace');
        $time=time();
        //按照 权重取规则  数量越大  权重越大  先进行规则
        $replaceList = $replaceMdl ->getList('*',array('material_bn' => $order_items['bn'],'start_time|lthan'=>$time,'end_time|than'=>$time,'disabled'=>'true'), 0, -1, 'priority DESC');
        //如果 该物料没有替换规则  则返回
        if(empty($replaceList)) return false;
        //如果该物料  有替换规则则进行 替换操作
        foreach ($replaceList as $s1 => $shop1) {
            $shopdata1 = explode(',',$shop1['shopIds']);
            if (!in_array($shop_id,$shopdata1)) {
                unset($replaceList[$s1]);
            }
        }
        $arr=array();
        $i=0;
        error_log(var_export($replaceList,true)."\n\t",3,PUBLIC_DIR."/replaceList1.log");
        foreach($replaceList as $k=>$v){
            //如果当前物料数量 小于 当前规则必须满足替换的数量 直接跳过该规则
            if($order_items['nums'] < $v['num']) continue;
            $repalce_num =floor($order_items['nums']/$v['num']);//向下取整   (该规则替换物料的倍数 * replaceNum最终为 替换物料的数量)
            $left=$order_items['nums']%$v['num']; //取剩下的
            $arr[$i]['rep_material_bn']=$v['rep_material_bn'];                   // 替换物料编码
            $arr[$i]['ti_num']=$v['num']*$repalce_num;                            //原物料有几个被此时的替换物料替换了
            $arr[$i]['repalce_num']=$repalce_num*$v['replaceNum'];               //替换物料的个数
            $arr[$i]['rep_material_name']=$v['rep_material_name'];  //替换物料的名称
            $arr[$i]['rep_bm_id']=$v['rep_bm_id'];                  //替换物料的 id
            $order_items['nums']=$left;                                          //此时原物料还剩几个
            $i++;
        }
        if($order_items['nums'] > 0){
            $arr[$i]['rep_material_bn']=$order_items['bn'];
            $arr[$i]['repalce_num']=$order_items['nums'];
            $arr[$i]['ti_num']=$order_items['nums'];
            $arr[$i]['rep_material_name']=$order_items['name'];
            $arr[$i]['rep_bm_id']=$order_items['product_id'];
            //如果两者数据相等  说明该物料有规则  但是并不符合  不能走替换
            if($pre_nums == $order_items['nums']) return false;
        }
        //走到这一定会有替换
        return $arr;
    }


    /**根据替换返回的参数 创建新的数据  objects和items
     * @param $data
     * @param $items
     */
    public function createObjectItems($data,$items){
        //这时 有替换  修改原订单明细的状态   原订单明细作废
        $oOrderItemMdl = app::get('ome')->model('order_items');
        $oOrdersObjMdl = app::get('ome')->model('order_objects');
//
        $materialsaleMdl = app::get('material')->model('sales_material');
        $materialextMdl = app::get('material')->model('sales_material_ext');
        $sm_id = $materialsaleMdl ->getlist('sm_id,sales_material_type',array('sales_material_bn'=>$data['rep_material_bn']));
        if($sm_id[0]['sales_material_type'] == '1'){
            $obj_type = 'goods';
            $obj_alias = 'goods';
            $item_type = 'product';
        }elseif ($sm_id[0]['sales_material_type'] == '2') {
            $obj_type = 'pkg';
            $obj_alias = 'pkg';
            $item_type = 'pkg';
        }elseif ($sm_id[0]['sales_material_type'] == '3') {
            $obj_type = 'gift';
            $obj_alias = 'gift';
            $item_type = 'gift';
        }
        //跟據替換物料的  id  查找重量
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $weight2 = $basicMaterialExtObj->dump(array('bm_id'=>$data['rep_bm_id']), 'weight');
        //重新生成  objects和items
        //相同字段数据
        $same_data['shop_goods_id']=0;//暂时不知道
        $same_data['order_id']=$items['order_id'];
        $same_data['bn']=$data['rep_material_bn'];//替换物料的编码
        $same_data['name']=$data['rep_material_name'];
        $same_data['price']=$items['price']*$data['ti_num']/$data['repalce_num'];  //原来的单价X被替换的数量 除以  现在的数量
        $same_data['amount']=$items['price']*$data['ti_num']; //小计  原单价X被替换数量
        $same_data['weight']=$data['repalce_num']*$weight2['weight'];  //替换物料的数量 X 替换物料的单个重量
        $same_data['pmt_price']=$items['pmt_price']*($data['ti_num']/$items['nums']);  //优惠价格  原优惠加个 X 被替换数量/原总数量
        $same_data['sale_price']=$items['price']*$data['ti_num'] - $items['pmt_price']*($data['ti_num']/$items['nums']); //小计-优惠
        $same_data['divide_order_fee']=$items['divide_order_fee']*($data['ti_num']/$items['nums']);//优惠价格  原优惠加个 X 被替换数量/原总数量
        $same_data['part_mjz_discount']=$items['part_mjz_discount']*($data['ti_num']/$items['nums']);//优惠分摊  原优惠分摊 X 被替换数量/原总数量
        //objects数据
        $obj_data['obj_type']=$obj_type;
        $obj_data['obj_alias']=$obj_alias;
        $obj_data['goods_id']=$data['rep_bm_id'];//暂时不知道
        $obj_data['score']=$items['score'];//  积分 暂时用原积分
        $obj_data['quantity']=$data['repalce_num'];          // 替换无聊的数量
        $new_object_data=array_merge($same_data,$obj_data);
        $re=$oOrdersObjMdl->insert($new_object_data);
        //items数据
        $items_data['product_id']=$data['rep_bm_id'];
        $items_data['shop_product_id']=$items['rep_bm_id'];
        $items_data['nums']=$data['repalce_num'];
        $items_data['sendnum']=0;
        $items_data['return_num']=0;
        $items_data['item_type']=$item_type;

        $items_data['obj_id']=$re;
        $new_items_data=array_merge($same_data,$items_data);
        $oOrderItemMdl->insert($new_items_data);
    }


    public function dealdata($items_data,$shop_id)
    {

        $i=0;
        static $arr1=array();
        foreach($items_data as $key=>$v){
            $result=$this->checkreplace($v,$shop_id);
            // if($result['is_replace']==1){
            //     $i++;
            //     $arr1[]=$i;
            // }
            $new_data[]=$result['data'];
        }
        //if($i==0)  {
        return $this->threeToTwo($new_data);;
        //}
        //del by ldward 20180627 删除多次重算的逻辑
        // $arr2=$this->threeToTwo($new_data);
        // if($arr2){
        //    $re=$this->mergedata($arr2);
        //    return $this->dealdata($re,$shop_id);
        // }
        //end by
    }

    public function checkreplace($items_new,$shop_id)
    {
        $pre_nums=$items_new['repalce_num'];
        $replaceMdl = app::get('material')->model('basic_replace');
        $time=time();
        //按照 权重取规则  数量越大  权重越大  先进行规则
        $replaceList = $replaceMdl ->getList('*',array('material_bn' => $items_new['rep_material_bn'],'start_time|lthan'=>$time,'end_time|than'=>$time,'disabled'=>'true'), 0, -1, 'priority DESC');

//        var_dump($replaceList);die;
        //如果 该物料没有替换规则  则返回
        if(empty($replaceList)) 
        {
            $data['is_replace']=0;
            $items_new['is_replace']=0;
            $items_new['rep_item_id']=$items_new['item_id'];
            $data['data'][]=$items_new;
            return $data;
        }
        //如果该物料  有替换规则则进行 替换操作
        foreach ($replaceList as $s1 => $shop1) {
            $shopdata1 = explode(',',$shop1['shopIds']);
            if (!in_array($shop_id,$shopdata1)) {
                unset($replaceList[$s1]);
            }
        }
        $arr=array();
        $i=0;
        foreach($replaceList as $k=>$v)
        {
            //如果当前物料数量 小于 当前规则必须满足替换的数量 直接跳过该规则
            if($items_new['repalce_num'] < $v['num']) continue;
            $repalce_num =floor($items_new['repalce_num']/$v['num']);//向下取整   (该规则替换物料的倍数 * replaceNum最终为 替换物料的数量)
            $left=$items_new['repalce_num']%$v['num']; //取剩下的
            $arr[$i]['rep_material_bn']=$v['rep_material_bn'];                   // 替换物料编码
            $arr[$i]['ti_num']=$v['num']*$repalce_num;                            //原物料有几个被此时的替换物料替换了
            $arr[$i]['repalce_num']=$repalce_num*$v['replaceNum'];               //替换物料的个数
            $arr[$i]['rep_material_name']=$v['rep_material_name'];  //替换物料的名称
            $arr[$i]['rep_bm_id']=$v['rep_bm_id'];
            $arr[$i]['price']=$items_new['price']*$v['num']/$v['replaceNum'];//替换物料的 id
            $arr[$i]['pmt_price']=$items_new['pmt_price']*$v['num']/$v['replaceNum'];//替换物料的 id
            $arr[$i]['part_mjz_discount']=$items_new['part_mjz_discount']*$v['num']/$v['replaceNum'];//替换物料的 id
            $arr[$i]['rep_item_id']=$items_new['item_id'];//替换物料的 id
            $items_new['repalce_num']=$left;                                          //此时原物料还剩几个
            $i++;
        }
        if($items_new['repalce_num'] > 0)
        {
            $arr[$i]['rep_material_bn']=$items_new['rep_material_bn'];
            $arr[$i]['repalce_num']=$items_new['repalce_num'];
            $arr[$i]['ti_num']=$items_new['ti_num'];
            $arr[$i]['rep_material_name']=$items_new['rep_material_name'];
            $arr[$i]['rep_bm_id']=$items_new['rep_bm_id'];
            $arr[$i]['price']=$items_new['price'];
            $arr[$i]['pmt_price']=$items_new['pmt_price'];
            $arr[$i]['part_mjz_discount']=$items_new['part_mjz_discount'];
            $arr[$i]['rep_item_id']=$items_new['item_id'];//替换物料的 id
            //如果两者数据相等  说明该物料有规则  但是并不符合  不能走替换
            if($pre_nums == $items_new['repalce_num']) 
            {
                $data['is_replace']=0;
                $items_new['is_replace']=0;
                $data['data'][]=$items_new;
                return $data;
            }
        }
        $data['is_replace']=1;
        $data['data']=$arr;
        return $data;

    }

    public function threeToTwo($new_data)
    {
        foreach($new_data as $value)
        {
            foreach($value as $v){
                $arr2[]=$v;
            }
        }
        return $arr2;
    }

    public function mergedata($total_items_data){
        $count=count($total_items_data);
        $new_data=array();
        $j=1;
        foreach($total_items_data as $k=> $value){
            for($i=$j;$i<$count;$i++){
                if($value['rep_bm_id'] == $total_items_data[$i]['rep_bm_id']){
                    $price=($total_items_data[$k]['repalce_num']*$total_items_data[$k]['price']+$total_items_data[$i]['repalce_num']*$total_items_data[$i]['price'])/($total_items_data[$k]['repalce_num']+$total_items_data[$i]['repalce_num']);
                    $pmt_price=($total_items_data[$k]['repalce_num']*$total_items_data[$k]['pmt_price']+$total_items_data[$i]['repalce_num']*$total_items_data[$i]['pmt_price'])/($total_items_data[$k]['repalce_num']+$total_items_data[$i]['repalce_num']);
                    $part_mjz_discount=($total_items_data[$k]['repalce_num']*$total_items_data[$k]['part_mjz_discount']+$total_items_data[$i]['repalce_num']*$total_items_data[$i]['part_mjz_discount'])/($total_items_data[$k]['repalce_num']+$total_items_data[$i]['repalce_num']);
                    $total_items_data[$k]['repalce_num']=$total_items_data[$k]['repalce_num']+$total_items_data[$i]['repalce_num'];
                    $total_items_data[$k]['ti_num']=$total_items_data[$k]['ti_num']+$total_items_data[$i]['ti_num'];
                    $total_items_data[$k]['price']=$price;
                    $total_items_data[$k]['pmt_price']=$pmt_price;
                    $total_items_data[$k]['part_mjz_discount']=$part_mjz_discount;
                }
            }
            $j=$j+1;
            $new_data[]=$total_items_data[$k];
        }
        if($new_data) {
            $newArr = $this->array_unset_tt($new_data,'rep_bm_id');
            return  $newArr;
        }
        return $total_items_data;


    }

    public function array_unset_tt($arr,$key){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                //有：销毁
                unset($value[$key]);
            }
            else{
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }



    public function createObjectItems_new($data,$order_id){

        //这时 有替换  修改原订单明细的状态   原订单明细作废
        $oOrderItemMdl = app::get('ome')->model('order_items');
        $oOrdersObjMdl = app::get('ome')->model('order_objects');
        $itemRepMdl = app::get('ome')->model('order_itemsRep');
        $_opinfo = kernel::single('ome_func')->getDesktopUser();
//
        $materialsaleMdl = app::get('material')->model('sales_material');
        //
        $sm_id = $materialsaleMdl ->getlist('sm_id,sales_material_type',array('sales_material_bn'=>$data['rep_material_bn']));
        //if($sm_id[0]['sales_material_type'] == '1'){
            $obj_type = 'goods';
            $obj_alias = 'goods';
            $item_type = 'product';
        // }elseif ($sm_id[0]['sales_material_type'] == '2') {
        //     $obj_type = 'pkg';
        //     $obj_alias = 'pkg';
        //     $item_type = 'pkg';
        // }elseif ($sm_id[0]['sales_material_type'] == '3') {
        //     $obj_type = 'gift';
        //     $obj_alias = 'gift';
        //     $item_type = 'gift';
        // }
        //跟據替換物料的  id  查找重量
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $weight2 = $basicMaterialExtObj->dump(array('bm_id'=>$data['rep_bm_id']), 'weight');
//        $price = $basicMaterialExtObj->dump(array('bm_id'=>$data['rep_bm_id']), 'retail_price');
        //重新生成  objects和items
        //相同字段数据
        $same_data['shop_goods_id']=0;//暂时不知道
        $same_data['order_id']=$order_id;
        $same_data['bn']=$data['rep_material_bn'];//替换物料的编码
        $same_data['name']=$data['rep_material_name'];
        $same_data['price']=$data['price']; //原来的单价X被替换的数量 除以  现在的数量
        $same_data['amount']=$data['price']*$data['repalce_num']; //小计  原单价X被替换数量
        $same_data['weight']=$data['repalce_num']*$weight2['weight'];  //替换物料的数量 X 替换物料的单个重量
        $same_data['pmt_price']=$data['pmt_price']*$data['repalce_num'];  //优惠价格  原优惠加个 X 被替换数量/原总数量
        $same_data['sale_price']=$data['price']*$data['repalce_num'] - $data['pmt_price']*$data['repalce_num']; //小计-优惠
        $same_data['divide_order_fee']=$same_data['sale_price']-$data['part_mjz_discount']*$data['repalce_num'];//优惠价格  原优惠加个 X 被替换数量/原总数量
        $same_data['part_mjz_discount']=$data['part_mjz_discount']*$data['repalce_num'];
        //objects数据
        $obj_data['obj_type']=$obj_type;
        $obj_data['obj_alias']=$obj_alias;
        $obj_data['goods_id']=$data['rep_bm_id'];//暂时不知道

        $obj_data['quantity']=$data['repalce_num'];          // 替换无聊的数量
        $new_object_data=array_merge($same_data,$obj_data);
        $re=$oOrdersObjMdl->insert($new_object_data);
        //items数据
        $items_data['product_id']=$data['rep_bm_id'];

        $items_data['nums']=$data['repalce_num'];
        $items_data['sendnum']=0;
        $items_data['return_num']=0;
        $items_data['item_type']=$item_type;
        $items_data['is_replace']='true';
        $items_data['obj_id']=$re;
        $new_items_data=array_merge($same_data,$items_data);
        $newitem_id=$oOrderItemMdl->insert($new_items_data);

        //为了统计报表用，添加替换明细
        $itemList_rep = $oOrderItemMdl ->getlist('*',array('item_id'=>$data['rep_item_id']));
        $itemList=$itemList_rep[0];
        //$itemList['rep_num']=1;//替换前数量
        $itemList['newitem_id']=$newitem_id;
        $itemList['op_time']=time();
        $itemList['op_id']=$_opinfo['op_id'] ? $_opinfo['op_id'] : 16777215;
        $itemList['op_name']=$_opinfo['op_name'] ? $_opinfo['op_name'] : "系统";
        unset($itemList['item_id']);
        if($itemList['bn']!=$same_data['bn']){
            $itemRepMdl->save($itemList);

            #记录操作日志
            $oOperation_log = app::get('ome')->model('operation_log');
            $oOperation_log->write_log('order_edit@ome',$order_id,"订单物料明细".$itemList['bn']."自动替换为".$same_data['bn']);
        }

    }
}